from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.spit.models import Spit
from apps.spit.serializers import SpitSerialzier


class SpitView(ModelViewSet):
    # 制定查询集属性
    queryset = Spit.objects.filter(parent=None)
    # 制定序列化器属性
    serializer_class = SpitSerialzier

    def perform_authentication(self, request):
        pass
    @action(methods=['put'], detail=True)
    def collect(self, request, pk):
        user = request.user
        if not user.is_authenticated():
            return Response({
                'message': '用户未登录',
                'success': False
            },status=400)
        # 获取数据
        spit = Spit.objects.get(id=pk)
        # 判断当前收藏状态
        if spit.collected:
            spit.collected = False
        else:
            spit.collected = True
        spit.save()
        return Response({
            'message': 'OK',
            'success': True
        })

    @action(methods=['put'], detail=True)
    def updatethumbup(self, request, pk):
        user = request.user
        if not user.is_authenticated():
            return Response({
                'message': '用户未登录',
                'success': False
            },status=400)
        # 获取数据
        spit = Spit.objects.get(id=pk)
        # 判断当前点赞状态
        if spit.hasthumbup:
            spit.hasthumbup = False
            spit.thumbup -= 1
        else:
            spit.hasthumbup = True
            spit.thumbup += 1
        spit.save()
        return Response({
            'message': 'OK',
            'success': True
        })

    @action(methods=['get'], detail=True)
    def children(self, request, pk):
        children_spits = Spit.objects.filter(parent_id=pk).order_by('-publishtime')
        ser = self.get_serializer(children_spits, many=True)
        return Response(ser.data)